package com.kyz.speechsdk.engine.helper;

import android.text.TextUtils;

import com.kyz.speechsdk.engine.entity.ExcelData;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

/**
 * create by ZhongZihao on 2020/12/29
 */
public class LocalStoreHelper {
    // 本地多个关键词,或多个回答，用 “ |||” 连接
    private static final String orFlagStr = "\\|\\|\\|";

    private static List<ExcelData> localDatas = new ArrayList<>();

    public static List<ExcelData> getLocalDatas() {
        return localDatas;
    }

    public static boolean loadExcelConfigure(String filePath) {
        if (!checkPath(filePath)) return false;
        localDatas.clear();
        File file = new File(filePath);
        try {
            Workbook workbook = Workbook.getWorkbook(file);
            Cell cell; // 单个单元格
            long starttime = System.currentTimeMillis();
            Sheet[] sheets = workbook.getSheets();
            //获取Excel所有的工作表，一个工作表代表一个语料库，参考本地语料库格式
            for (int i = 0; i < sheets.length; i++) {
                Sheet sheet = sheets[i];
                //获取当前语料库的所有行。第1行是提示则跳过，
                for (int row = 1; row < sheet.getRows(); row++) {
                    cell = sheet.getCell(0, row);
                    String keywords = cell.getContents();
                    if (TextUtils.isEmpty(keywords)) continue;
                    cell = sheet.getCell(1, row);
                    String answers = cell.getContents();
                    if (TextUtils.isEmpty(answers)) continue;
                    List<String> keywordList = new ArrayList<>(Arrays.asList(keywords.split(orFlagStr)));
                    List<String> answerList = new ArrayList<>(Arrays.asList(answers.split(orFlagStr)));
                    localDatas.add(new ExcelData(keywordList, answerList, sheet.getName(), i));
                }
            }
            System.out.println("读取数据完成：耗时" + (System.currentTimeMillis() - starttime) + "ms");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    //判断路径是否符合
    private static boolean checkPath(String filePath) {
        if (!TextUtils.isEmpty(filePath) && new File(filePath).exists()) {
            return filePath.toLowerCase().endsWith(".xls") || filePath.toLowerCase().endsWith(".xlsx");
        }
        return false;
    }

    public static ExcelData matchAnswer(String sentence) {
        if (localDatas.isEmpty()) return null;
        for (ExcelData localData : localDatas) {
            for (String keyword : localData.getKeywords()) {
                if (StringMatcher.isMatch(sentence, keyword)) {
                    return localData;
                }
            }
        }
        return null;
    }
}
